home *** CD-ROM | disk | FTP | other *** search
/ The CICA Windows Explosion! / The CICA Windows Explosion! - Disc 2.iso / nt / emacssrc.zip / EMACSSRC.TAR / emacs-19.17 / src / search.c < prev    next >
C/C++ Source or Header  |  1993-10-16  |  48KB  |  1,561 lines

  1. /* String search routines for GNU Emacs.
  2.    Copyright (C) 1985, 1986, 1987, 1993 Free Software Foundation, Inc.
  3.  
  4. This file is part of GNU Emacs.
  5.  
  6. GNU Emacs is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 1, or (at your option)
  9. any later version.
  10.  
  11. GNU Emacs is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with GNU Emacs; see the file COPYING.  If not, write to
  18. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  19.  
  20.  
  21. #include "config.h"
  22. #include "lisp.h"
  23. #include "syntax.h"
  24. #include "buffer.h"
  25. #include "commands.h"
  26. #include "blockinput.h"
  27.  
  28. #include <sys/types.h>
  29. #include "regex.h"
  30.  
  31. #ifdef STDC_HEADERS
  32. #include <stdlib.h>
  33. #endif
  34. #include "search_p.h"
  35. #include "search_d.h"
  36. #include "intervals_p.h"
  37. #include "alloca_p.h"
  38. #include "insdel_p.h"
  39. static void matcher_overflow _P_((void));
  40. static Lisp_Object search_command _P_((Lisp_Object string, Lisp_Object bound,
  41.                                        Lisp_Object noerror, Lisp_Object count,
  42.                                        int direction, int RE));
  43. static Lisp_Object wordify _P_((Lisp_Object string));
  44. static Lisp_Object match_limit _P_((Lisp_Object num, int beginningp));
  45.  
  46. #ifndef max
  47. #define max(a, b) ((a) > (b) ? (a) : (b))
  48. #endif
  49. #ifndef min
  50. #define min(a, b) ((a) < (b) ? (a) : (b))
  51. #endif
  52.  
  53. /* We compile regexps into this buffer and then use it for searching. */
  54.  
  55. struct re_pattern_buffer searchbuf;
  56.  
  57. char search_fastmap[0400];
  58.  
  59. /* Last regexp we compiled */
  60.  
  61. Lisp_Object last_regexp;
  62.  
  63. /* Every call to re_match, etc., must pass &search_regs as the regs
  64.    argument unless you can show it is unnecessary (i.e., if re_match
  65.    is certainly going to be called again before region-around-match
  66.    can be called).
  67.  
  68.    Since the registers are now dynamically allocated, we need to make
  69.    sure not to refer to the Nth register before checking that it has
  70.    been allocated by checking search_regs.num_regs.
  71.  
  72.    The regex code keeps track of whether it has allocated the search
  73.    buffer using bits in searchbuf.  This means that whenever you
  74.    compile a new pattern, it completely forgets whether it has
  75.    allocated any registers, and will allocate new registers the next
  76.    time you call a searching or matching function.  Therefore, we need
  77.    to call re_set_registers after compiling a new pattern or after
  78.    setting the match registers, so that the regex functions will be
  79.    able to free or re-allocate it properly.  */
  80. static struct re_registers search_regs;
  81.  
  82. /* The buffer in which the last search was performed, or
  83.    Qt if the last search was done in a string;
  84.    Qnil if no searching has been done yet.  */
  85. static Lisp_Object last_thing_searched;
  86.  
  87. /* error condition signalled when regexp compile_pattern fails */
  88.  
  89. Lisp_Object Qinvalid_regexp;
  90.  
  91. static void
  92. matcher_overflow ()
  93. {
  94.   error ("Stack overflow in regexp matcher");
  95. }
  96.  
  97. #ifdef __STDC__
  98. #define CONST const
  99. #endif
  100. #ifdef WINDOWSNT
  101. #define CONST const
  102. #endif
  103. #ifndef CONST
  104. #define CONST
  105. #endif
  106.  
  107. /* Compile a regexp and signal a Lisp error if anything goes wrong.  */
  108.  
  109. _VOID_
  110. compile_pattern (pattern, bufp, regp, translate)
  111.      Lisp_Object pattern;
  112.      struct re_pattern_buffer *bufp;
  113.      struct re_registers *regp;
  114.      char *translate;
  115. {
  116.   CONST char *val;
  117.   Lisp_Object dummy;
  118.  
  119.   if (EQ (pattern, last_regexp)
  120.       && translate == bufp->translate)
  121.     return;
  122.  
  123.   last_regexp = Qnil;
  124.   bufp->translate = translate;
  125.   BLOCK_INPUT;
  126.   val = re_compile_pattern ((CONST char *) XSTRING (pattern)->data,
  127.                 XSTRING (pattern)->size,
  128.                 bufp);
  129.   UNBLOCK_INPUT;
  130.   if (val)
  131.     {
  132.       dummy = build_string ((char *)val);
  133.       while (1)
  134.     Fsignal (Qinvalid_regexp, Fcons (dummy, Qnil));
  135.     }
  136.  
  137.   last_regexp = pattern;
  138.  
  139.   /* Advise the searching functions about the space we have allocated
  140.      for register data.  */
  141.   BLOCK_INPUT;
  142.   if (regp)
  143.     re_set_registers (bufp, regp, regp->num_regs, regp->start, regp->end);
  144.   UNBLOCK_INPUT;
  145.  
  146.   return;
  147. }
  148.  
  149. /* Error condition used for failing searches */
  150. Lisp_Object Qsearch_failed;
  151.  
  152. Lisp_Object
  153. signal_failure (arg)
  154.      Lisp_Object arg;
  155. {
  156.   Fsignal (Qsearch_failed, Fcons (arg, Qnil));
  157.   return Qnil;
  158. }
  159.  
  160. DEFUN ("looking-at", Flooking_at, Slooking_at, 1, 1, 0,
  161.   "Return t if text after point matches regular expression PAT.\n\
  162. This function modifies the match data that `match-beginning',\n\
  163. `match-end' and `match-data' access; save and restore the match\n\
  164. data if you want to preserve them.")
  165.   (string)
  166.      Lisp_Object string;
  167. {
  168.   Lisp_Object val;
  169.   unsigned char *p1, *p2;
  170.   int s1, s2;
  171.   register int i;
  172.  
  173.   CHECK_STRING (string, 0);
  174.   compile_pattern (string, &searchbuf, &search_regs,
  175.            !NILP (current_buffer->case_fold_search) ? DOWNCASE_TABLE : 0);
  176.  
  177.   immediate_quit = 1;
  178.   QUIT;            /* Do a pending quit right away, to avoid paradoxical behavior */
  179.  
  180.   /* Get pointers and sizes of the two strings
  181.      that make up the visible portion of the buffer. */
  182.  
  183.   p1 = BEGV_ADDR;
  184.   s1 = GPT - BEGV;
  185.   p2 = GAP_END_ADDR;
  186.   s2 = ZV - GPT;
  187.   if (s1 < 0)
  188.     {
  189.       p2 = p1;
  190.       s2 = ZV - BEGV;
  191.       s1 = 0;
  192.     }
  193.   if (s2 < 0)
  194.     {
  195.       s1 = ZV - BEGV;
  196.       s2 = 0;
  197.     }
  198.   
  199.   i = re_match_2 (&searchbuf, (char *) p1, s1, (char *) p2, s2,
  200.           point - BEGV, &search_regs,
  201.           ZV - BEGV);
  202.   if (i == -2)
  203.     matcher_overflow ();
  204.  
  205.   val = (0 <= i ? Qt : Qnil);
  206.   for (i = 0; (unsigned)i < search_regs.num_regs; i++)
  207.     if (search_regs.start[i] >= 0)
  208.       {
  209.     search_regs.start[i] += BEGV;
  210.     search_regs.end[i] += BEGV;
  211.       }
  212.   XSET (last_thing_searched, Lisp_Buffer, current_buffer);
  213.   immediate_quit = 0;
  214.   return val;
  215. }
  216.  
  217. DEFUN ("string-match", Fstring_match, Sstring_match, 2, 3, 0,
  218.   "Return index of start of first match for REGEXP in STRING, or nil.\n\
  219. If third arg START is non-nil, start search at that index in STRING.\n\
  220. For index of first char beyond the match, do (match-end 0).\n\
  221. `match-end' and `match-beginning' also give indices of substrings\n\
  222. matched by parenthesis constructs in the pattern.")
  223.   (regexp, string, start)
  224.      Lisp_Object regexp, string, start;
  225. {
  226.   int val;
  227.   int s;
  228.  
  229.   CHECK_STRING (regexp, 0);
  230.   CHECK_STRING (string, 1);
  231.  
  232.   if (NILP (start))
  233.     s = 0;
  234.   else
  235.     {
  236.       int len = XSTRING (string)->size;
  237.  
  238.       CHECK_NUMBER (start, 2);
  239.       s = XINT (start);
  240.       if (s < 0 && -s <= len)
  241.     s = len - s;
  242.       else if (0 > s || s > len)
  243.     args_out_of_range (string, start);
  244.     }
  245.  
  246.   compile_pattern (regexp, &searchbuf, &search_regs,
  247.            !NILP (current_buffer->case_fold_search) ? DOWNCASE_TABLE : 0);
  248.   immediate_quit = 1;
  249.   val = re_search (&searchbuf, (char *) XSTRING (string)->data,
  250.            XSTRING (string)->size, s, XSTRING (string)->size - s,
  251.            &search_regs);
  252.   immediate_quit = 0;
  253.   last_thing_searched = Qt;
  254.   if (val == -2)
  255.     matcher_overflow ();
  256.   if (val < 0) return Qnil;
  257.   return make_number (val);
  258. }
  259.  
  260. /* Match REGEXP against STRING, searching all of STRING,
  261.    and return the index of the match, or negative on failure.
  262.    This does not clobber the match data.  */
  263.  
  264. int
  265. fast_string_match (regexp, string)
  266.      Lisp_Object regexp, string;
  267. {
  268.   int val;
  269.  
  270.   compile_pattern (regexp, &searchbuf, 0, 0);
  271.   immediate_quit = 1;
  272.   val = re_search (&searchbuf, (char *) XSTRING (string)->data,
  273.            XSTRING (string)->size, 0, XSTRING (string)->size,
  274.            0);
  275.   immediate_quit = 0;
  276.   return val;
  277. }
  278.  
  279. /* Search for COUNT instances of the character TARGET, starting at START.
  280.    If COUNT is negative, search backwards.
  281.  
  282.    If we find COUNT instances, set *SHORTAGE to zero, and return the
  283.    position after the COUNTth match.  Note that for reverse motion
  284.    this is not the same as the usual convention for Emacs motion commands.
  285.  
  286.    If we don't find COUNT instances before reaching the end of the
  287.    buffer (or the beginning, if scanning backwards), set *SHORTAGE to
  288.    the number of TARGETs left unfound, and return the end of the
  289.    buffer we bumped up against.  */
  290.  
  291. int
  292. scan_buffer (target, start, count, shortage)
  293.      int *shortage, start;
  294.      register int count, target;
  295. {
  296.   int limit = ((count > 0) ? ZV - 1 : BEGV);
  297.   int direction = ((count > 0) ? 1 : -1);
  298.  
  299.   register unsigned char *cursor;
  300.   unsigned char *base;
  301.  
  302.   register int ceiling;
  303.   register unsigned char *ceiling_addr;
  304.  
  305.   if (shortage != 0)
  306.     *shortage = 0;
  307.  
  308.   immediate_quit = 1;
  309.  
  310.   if (count > 0)
  311.     while (start != limit + 1)
  312.       {
  313.     ceiling =  BUFFER_CEILING_OF (start);
  314.     ceiling = min (limit, ceiling);
  315.     ceiling_addr = &FETCH_CHAR (ceiling) + 1;
  316.     base = (cursor = &FETCH_CHAR (start));
  317.     while (1)
  318.       {
  319.         while (*cursor != target && ++cursor != ceiling_addr)
  320.           ;
  321.         if (cursor != ceiling_addr)
  322.           {
  323.         if (--count == 0)
  324.           {
  325.             immediate_quit = 0;
  326.             return (start + cursor - base + 1);
  327.           }
  328.         else
  329.           if (++cursor == ceiling_addr)
  330.             break;
  331.           }
  332.         else
  333.           break;
  334.       }
  335.     start += cursor - base;
  336.       }
  337.   else
  338.     {
  339.       start--;            /* first character we scan */
  340.       while (start > limit - 1)
  341.     {            /* we WILL scan under start */
  342.       ceiling =  BUFFER_FLOOR_OF (start);
  343.       ceiling = max (limit, ceiling);
  344.       ceiling_addr = &FETCH_CHAR (ceiling) - 1;
  345.       base = (cursor = &FETCH_CHAR (start));
  346.       cursor++;
  347.       while (1)
  348.         {
  349.           while (--cursor != ceiling_addr && *cursor != target)
  350.         ;
  351.           if (cursor != ceiling_addr)
  352.         {
  353.           if (++count == 0)
  354.             {
  355.               immediate_quit = 0;
  356.               return (start + cursor - base + 1);
  357.             }
  358.         }
  359.           else
  360.         break;
  361.         }
  362.       start += cursor - base;
  363.     }
  364.     }
  365.   immediate_quit = 0;
  366.   if (shortage != 0)
  367.     *shortage = count * direction;
  368.   return (start + ((direction == 1 ? 0 : 1)));
  369. }
  370.  
  371. int
  372. find_next_newline (from, cnt)
  373.      register int from, cnt;
  374. {
  375.   return (scan_buffer ('\n', from, cnt, (int *) 0));
  376. }
  377.  
  378.  
  379. DEFUN ("skip-chars-forward", Fskip_chars_forward, Sskip_chars_forward, 1, 2, 0,
  380.   "Move point forward, stopping before a char not in CHARS, or at position LIM.\n\
  381. CHARS is like the inside of a `[...]' in a regular expression\n\
  382. except that `]' is never special and `\\' quotes `^', `-' or `\\'.\n\
  383. Thus, with arg \"a-zA-Z\", this skips letters stopping before first nonletter.\n\
  384. With arg \"^a-zA-Z\", skips nonletters stopping before first letter.\n\
  385. Returns the distance traveled, either zero or positive.")
  386.   (string, lim)
  387.      Lisp_Object string, lim;
  388. {
  389.   return skip_chars (1, 0, string, lim);
  390. }
  391.  
  392. DEFUN ("skip-chars-backward", Fskip_chars_backward, Sskip_chars_backward, 1, 2, 0,
  393.   "Move point backward, stopping after a char not in CHARS, or at position LIM.\n\
  394. See `skip-chars-forward' for details.\n\
  395. Returns the distance traveled, either zero or negative.")
  396.   (string, lim)
  397.      Lisp_Object string, lim;
  398. {
  399.   return skip_chars (0, 0, string, lim);
  400. }
  401.  
  402. DEFUN ("skip-syntax-forward", Fskip_syntax_forward, Sskip_syntax_forward, 1, 2, 0,
  403.   "Move point forward across chars in specified syntax classes.\n\
  404. SYNTAX is a string of syntax code characters.\n\
  405. Stop before a char whose syntax is not in SYNTAX, or at position LIM.\n\
  406. If SYNTAX starts with ^, skip characters whose syntax is NOT in SYNTAX.\n\
  407. This function returns the distance traveled, either zero or positive.")
  408.   (syntax, lim)
  409.      Lisp_Object syntax, lim;
  410. {
  411.   return skip_chars (1, 1, syntax, lim);
  412. }
  413.  
  414. DEFUN ("skip-syntax-backward", Fskip_syntax_backward, Sskip_syntax_backward, 1, 2, 0,
  415.   "Move point backward across chars in specified syntax classes.\n\
  416. SYNTAX is a string of syntax code characters.\n\
  417. Stop on reaching a char whose syntax is not in SYNTAX, or at position LIM.\n\
  418. If SYNTAX starts with ^, skip characters whose syntax is NOT in SYNTAX.\n\
  419. This function returns the distance traveled, either zero or negative.")
  420.   (syntax, lim)
  421.      Lisp_Object syntax, lim;
  422. {
  423.   return skip_chars (0, 1, syntax, lim);
  424. }
  425.  
  426. Lisp_Object
  427. skip_chars (forwardp, syntaxp, string, lim)
  428.      int forwardp, syntaxp;
  429.      Lisp_Object string, lim;
  430. {
  431.   register unsigned char *p, *pend;
  432.   register unsigned char c;
  433.   unsigned char fastmap[0400];
  434.   int negate = 0;
  435.   register int i;
  436.  
  437.   CHECK_STRING (string, 0);
  438.  
  439.   if (NILP (lim))
  440.     XSET (lim, Lisp_Int, forwardp ? ZV : BEGV);
  441.   else
  442.     CHECK_NUMBER_COERCE_MARKER (lim, 1);
  443.  
  444. #if 0                /* This breaks some things... jla. */
  445.   /* In any case, don't allow scan outside bounds of buffer.  */
  446.   if (XFASTINT (lim) > ZV)
  447.     XFASTINT (lim) = ZV;
  448.   if (XFASTINT (lim) < BEGV)
  449.     XFASTINT (lim) = BEGV;
  450. #endif
  451.  
  452.   p = XSTRING (string)->data;
  453.   pend = p + XSTRING (string)->size;
  454.   bzero (fastmap, sizeof fastmap);
  455.  
  456.   if (p != pend && *p == '^')
  457.     {
  458.       negate = 1; p++;
  459.     }
  460.  
  461.   /* Find the characters specified and set their elements of fastmap.
  462.      If syntaxp, each character counts as itself.
  463.      Otherwise, handle backslashes and ranges specially  */
  464.  
  465.   while (p != pend)
  466.     {
  467.       c = *p++;
  468.       if (syntaxp)
  469.     fastmap[c] = 1;
  470.       else
  471.     {
  472.       if (c == '\\')
  473.         {
  474.           if (p == pend) break;
  475.           c = *p++;
  476.         }
  477.       if (p != pend && *p == '-')
  478.         {
  479.           p++;
  480.           if (p == pend) break;
  481.           while (c <= *p)
  482.         {
  483.           fastmap[c] = 1;
  484.           c++;
  485.         }
  486.           p++;
  487.         }
  488.       else
  489.         fastmap[c] = 1;
  490.     }
  491.     }
  492.  
  493.   /* If ^ was the first character, complement the fastmap. */
  494.  
  495.   if (negate)
  496.     for (i = 0; i < sizeof fastmap; i++)
  497.       fastmap[i] ^= 1;
  498.  
  499.   {
  500.     int start_point = point;
  501.  
  502.     immediate_quit = 1;
  503.     if (syntaxp)
  504.       {
  505.  
  506.     if (forwardp)
  507.       {
  508.         while (point < XINT (lim)
  509.            && fastmap[(unsigned char) syntax_code_spec[(int) SYNTAX (FETCH_CHAR (point))]])
  510.           SET_PT (point + 1);
  511.       }
  512.     else
  513.       {
  514.         while (point > XINT (lim)
  515.            && fastmap[(unsigned char) syntax_code_spec[(int) SYNTAX (FETCH_CHAR (point - 1))]])
  516.           SET_PT (point - 1);
  517.       }
  518.       }
  519.     else
  520.       {
  521.     if (forwardp)
  522.       {
  523.         while (point < XINT (lim) && fastmap[FETCH_CHAR (point)])
  524.           SET_PT (point + 1);
  525.       }
  526.     else
  527.       {
  528.         while (point > XINT (lim) && fastmap[FETCH_CHAR (point - 1)])
  529.           SET_PT (point - 1);
  530.       }
  531.       }
  532.     immediate_quit = 0;
  533.  
  534.     return make_number (point - start_point);
  535.   }
  536. }
  537.  
  538. /* Subroutines of Lisp buffer search functions. */
  539.  
  540. static Lisp_Object
  541. search_command (string, bound, noerror, count, direction, RE)
  542.      Lisp_Object string, bound, noerror, count;
  543.      int direction;
  544.      int RE;
  545. {
  546.   register int np;
  547.   int lim;
  548.   int n = direction;
  549.  
  550.   if (!NILP (count))
  551.     {
  552.       CHECK_NUMBER (count, 3);
  553.       n *= XINT (count);
  554.     }
  555.  
  556.   CHECK_STRING (string, 0);
  557.   if (NILP (bound))
  558.     lim = n > 0 ? ZV : BEGV;
  559.   else
  560.     {
  561.       CHECK_NUMBER_COERCE_MARKER (bound, 1);
  562.       lim = XINT (bound);
  563.       if (n > 0 ? lim < point : lim > point)
  564.     error ("Invalid search bound (wrong side of point)");
  565.       if (lim > ZV)
  566.     lim = ZV;
  567.       if (lim < BEGV)
  568.     lim = BEGV;
  569.     }
  570.  
  571.   np = search_buffer (string, point, lim, n, RE,
  572.               (!NILP (current_buffer->case_fold_search)
  573.                ? XSTRING (current_buffer->case_canon_table)->data : 0),
  574.               (!NILP (current_buffer->case_fold_search)
  575.                ? XSTRING (current_buffer->case_eqv_table)->data : 0));
  576.   if (np <= 0)
  577.     {
  578.       if (NILP (noerror))
  579.     return signal_failure (string);
  580.       if (!EQ (noerror, Qt))
  581.     {
  582.       if (lim < BEGV || lim > ZV)
  583.         abort ();
  584.       SET_PT (lim);
  585.       return Qnil;
  586. #if 0 /* This would be clean, but maybe programs depend on
  587.      a value of nil here.  */
  588.       np = lim;
  589. #endif
  590.     }
  591.       else
  592.     return Qnil;
  593.     }
  594.  
  595.   if (np < BEGV || np > ZV)
  596.     abort ();
  597.  
  598.   SET_PT (np);
  599.  
  600.   return make_number (np);
  601. }
  602.  
  603. /* search for the n'th occurrence of STRING in the current buffer,
  604.    starting at position POS and stopping at position LIM,
  605.    treating PAT as a literal string if RE is false or as
  606.    a regular expression if RE is true.
  607.  
  608.    If N is positive, searching is forward and LIM must be greater than POS.
  609.    If N is negative, searching is backward and LIM must be less than POS.
  610.  
  611.    Returns -x if only N-x occurrences found (x > 0),
  612.    or else the position at the beginning of the Nth occurrence
  613.    (if searching backward) or the end (if searching forward).  */
  614.  
  615. int
  616. search_buffer (string, pos, lim, n, RE, trt, inverse_trt)
  617.      Lisp_Object string;
  618.      int pos;
  619.      int lim;
  620.      int n;
  621.      int RE;
  622.      register unsigned char *trt;
  623.      register unsigned char *inverse_trt;
  624. {
  625.   int len = XSTRING (string)->size;
  626.   unsigned char *base_pat = XSTRING (string)->data;
  627.   register int *BM_tab;
  628.   int *BM_tab_base;
  629.   register int direction = ((n > 0) ? 1 : -1);
  630.   register int dirlen;
  631.   int infinity, limit, k, stride_for_teases;
  632.   register unsigned char *pat, *cursor, *p_limit;  
  633.   register int i, j;
  634.   unsigned char *p1, *p2;
  635.   int s1, s2;
  636.  
  637.   /* Null string is found at starting position.  */
  638.   if (!len)
  639.     return pos;
  640.  
  641.   if (RE)
  642.     compile_pattern (string, &searchbuf, &search_regs, (char *) trt);
  643.   
  644.   if (RE            /* Here we detect whether the */
  645.                 /* generality of an RE search is */
  646.                 /* really needed. */
  647.       /* first item is "exact match" */
  648.       && *(searchbuf.buffer) == (unsigned char) RE_EXACTN_VALUE
  649.       && (unsigned long)(searchbuf.buffer[1] + 2) == searchbuf.used) /*first is ONLY item */
  650.     {
  651.       RE = 0;            /* can do straight (non RE) search */
  652.       pat = (base_pat = (unsigned char *) searchbuf.buffer + 2);
  653.                 /* trt already applied */
  654.       len = searchbuf.used - 2;
  655.     }
  656.   else if (!RE)
  657.     {
  658.       pat = (unsigned char *) alloca (len);
  659.  
  660.       for (i = len; i--;)        /* Copy the pattern; apply trt */
  661.     *pat++ = (((int) trt) ? trt [*base_pat++] : *base_pat++);
  662.       pat -= len; base_pat = pat;
  663.     }
  664.  
  665.   if (RE)
  666.     {
  667.       immediate_quit = 1;    /* Quit immediately if user types ^G,
  668.                    because letting this function finish
  669.                    can take too long. */
  670.       QUIT;            /* Do a pending quit right away,
  671.                    to avoid paradoxical behavior */
  672.       /* Get pointers and sizes of the two strings
  673.      that make up the visible portion of the buffer. */
  674.  
  675.       p1 = BEGV_ADDR;
  676.       s1 = GPT - BEGV;
  677.       p2 = GAP_END_ADDR;
  678.       s2 = ZV - GPT;
  679.       if (s1 < 0)
  680.     {
  681.       p2 = p1;
  682.       s2 = ZV - BEGV;
  683.       s1 = 0;
  684.     }
  685.       if (s2 < 0)
  686.     {
  687.       s1 = ZV - BEGV;
  688.       s2 = 0;
  689.     }
  690.       while (n < 0)
  691.     {
  692.       int val;
  693.       val = re_search_2 (&searchbuf, (char *) p1, s1, (char *) p2, s2,
  694.                  pos - BEGV, lim - pos, &search_regs,
  695.                  /* Don't allow match past current point */
  696.                  pos - BEGV);
  697.       if (val == -2)
  698.         matcher_overflow ();
  699.       if (val >= 0)
  700.         {
  701.           j = BEGV;
  702.           for (i = 0; (unsigned)i < search_regs.num_regs; i++)
  703.         if (search_regs.start[i] >= 0)
  704.           {
  705.             search_regs.start[i] += j;
  706.             search_regs.end[i] += j;
  707.           }
  708.           XSET (last_thing_searched, Lisp_Buffer, current_buffer);
  709.           /* Set pos to the new position. */
  710.           pos = search_regs.start[0];
  711.         }
  712.       else
  713.         {
  714.           immediate_quit = 0;
  715.           return (n);
  716.         }
  717.       n++;
  718.     }
  719.       while (n > 0)
  720.     {
  721.       int val;
  722.       val = re_search_2 (&searchbuf, (char *) p1, s1, (char *) p2, s2,
  723.                  pos - BEGV, lim - pos, &search_regs,
  724.                  lim - BEGV);
  725.       if (val == -2)
  726.         matcher_overflow ();
  727.       if (val >= 0)
  728.         {
  729.           j = BEGV;
  730.           for (i = 0; (unsigned)i < search_regs.num_regs; i++)
  731.         if (search_regs.start[i] >= 0)
  732.           {
  733.             search_regs.start[i] += j;
  734.             search_regs.end[i] += j;
  735.           }
  736.           XSET (last_thing_searched, Lisp_Buffer, current_buffer);
  737.           pos = search_regs.end[0];
  738.         }
  739.       else
  740.         {
  741.           immediate_quit = 0;
  742.           return (0 - n);
  743.         }
  744.       n--;
  745.     }
  746.       immediate_quit = 0;
  747.       return (pos);
  748.     }
  749.   else                /* non-RE case */
  750.     {
  751. #ifdef C_ALLOCA
  752.       int BM_tab_space[0400];
  753.       BM_tab = &BM_tab_space[0];
  754. #else
  755.       BM_tab = (int *) alloca (0400 * sizeof (int));
  756. #endif
  757.       /* The general approach is that we are going to maintain that we know */
  758.       /* the first (closest to the present position, in whatever direction */
  759.       /* we're searching) character that could possibly be the last */
  760.       /* (furthest from present position) character of a valid match.  We */
  761.       /* advance the state of our knowledge by looking at that character */
  762.       /* and seeing whether it indeed matches the last character of the */
  763.       /* pattern.  If it does, we take a closer look.  If it does not, we */
  764.       /* move our pointer (to putative last characters) as far as is */
  765.       /* logically possible.  This amount of movement, which I call a */
  766.       /* stride, will be the length of the pattern if the actual character */
  767.       /* appears nowhere in the pattern, otherwise it will be the distance */
  768.       /* from the last occurrence of that character to the end of the */
  769.       /* pattern. */
  770.       /* As a coding trick, an enormous stride is coded into the table for */
  771.       /* characters that match the last character.  This allows use of only */
  772.       /* a single test, a test for having gone past the end of the */
  773.       /* permissible match region, to test for both possible matches (when */
  774.       /* the stride goes past the end immediately) and failure to */
  775.       /* match (where you get nudged past the end one stride at a time). */ 
  776.  
  777.       /* Here we make a "mickey mouse" BM table.  The stride of the search */
  778.       /* is determined only by the last character of the putative match. */
  779.       /* If that character does not match, we will stride the proper */
  780.       /* distance to propose a match that superimposes it on the last */
  781.       /* instance of a character that matches it (per trt), or misses */
  782.       /* it entirely if there is none. */  
  783.  
  784.       dirlen = len * direction;
  785.       infinity = dirlen - (lim + pos + len + len) * direction;
  786.       if (direction < 0)
  787.     pat = (base_pat += len - 1);
  788.       BM_tab_base = BM_tab;
  789.       BM_tab += 0400;
  790.       j = dirlen;        /* to get it in a register */
  791.       /* A character that does not appear in the pattern induces a */
  792.       /* stride equal to the pattern length. */
  793.       while (BM_tab_base != BM_tab)
  794.     {
  795.       *--BM_tab = j;
  796.       *--BM_tab = j;
  797.       *--BM_tab = j;
  798.       *--BM_tab = j;
  799.     }
  800.       i = 0;
  801.       while (i != infinity)
  802.     {
  803.       j = pat[i]; i += direction;
  804.       if (i == dirlen) i = infinity;
  805.       if ((int) trt)
  806.         {
  807.           k = (j = trt[j]);
  808.           if (i == infinity)
  809.         stride_for_teases = BM_tab[j];
  810.           BM_tab[j] = dirlen - i;
  811.           /* A translation table is accompanied by its inverse -- see */
  812.           /* comment following downcase_table for details */ 
  813.           while ((j = inverse_trt[j]) != k)
  814.         BM_tab[j] = dirlen - i;
  815.         }
  816.       else
  817.         {
  818.           if (i == infinity)
  819.         stride_for_teases = BM_tab[j];
  820.           BM_tab[j] = dirlen - i;
  821.         }
  822.       /* stride_for_teases tells how much to stride if we get a */
  823.       /* match on the far character but are subsequently */
  824.       /* disappointed, by recording what the stride would have been */
  825.       /* for that character if the last character had been */
  826.       /* different. */
  827.     }
  828.       infinity = dirlen - infinity;
  829.       pos += dirlen - ((direction > 0) ? direction : 0);
  830.       /* loop invariant - pos points at where last char (first char if reverse)
  831.      of pattern would align in a possible match.  */
  832.       while (n != 0)
  833.     {
  834.       if ((lim - pos - (direction > 0)) * direction < 0)
  835.         return (n * (0 - direction));
  836.       /* First we do the part we can by pointers (maybe nothing) */
  837.       QUIT;
  838.       pat = base_pat;
  839.       limit = pos - dirlen + direction;
  840.       limit = ((direction > 0)
  841.            ? BUFFER_CEILING_OF (limit)
  842.            : BUFFER_FLOOR_OF (limit));
  843.       /* LIMIT is now the last (not beyond-last!) value
  844.          POS can take on without hitting edge of buffer or the gap.  */
  845.       limit = ((direction > 0)
  846.            ? min (lim - 1, min (limit, pos + 20000))
  847.            : max (lim, max (limit, pos - 20000)));
  848.       if ((limit - pos) * direction > 20)
  849.         {
  850.           p_limit = &FETCH_CHAR (limit);
  851.           p2 = (cursor = &FETCH_CHAR (pos));
  852.           /* In this loop, pos + cursor - p2 is the surrogate for pos */
  853.           while (1)        /* use one cursor setting as long as i can */
  854.         {
  855.           if (direction > 0) /* worth duplicating */
  856.             {
  857.               /* Use signed comparison if appropriate
  858.              to make cursor+infinity sure to be > p_limit.
  859.              Assuming that the buffer lies in a range of addresses
  860.              that are all "positive" (as ints) or all "negative",
  861.              either kind of comparison will work as long
  862.              as we don't step by infinity.  So pick the kind
  863.              that works when we do step by infinity.  */
  864.               if ((int) (p_limit + infinity) > (int) p_limit)
  865.             while ((int) cursor <= (int) p_limit)
  866.               cursor += BM_tab[*cursor];
  867.               else
  868.             while ((unsigned int) cursor <= (unsigned int) p_limit)
  869.               cursor += BM_tab[*cursor];
  870.             }
  871.           else
  872.             {
  873.               if ((int) (p_limit + infinity) < (int) p_limit)
  874.             while ((int) cursor >= (int) p_limit)
  875.               cursor += BM_tab[*cursor];
  876.               else
  877.             while ((unsigned int) cursor >= (unsigned int) p_limit)
  878.               cursor += BM_tab[*cursor];
  879.             }
  880. /* If you are here, cursor is beyond the end of the searched region. */
  881.  /* This can happen if you match on the far character of the pattern, */
  882.  /* because the "stride" of that character is infinity, a number able */
  883.  /* to throw you well beyond the end of the search.  It can also */
  884.  /* happen if you fail to match within the permitted region and would */
  885.  /* otherwise try a character beyond that region */
  886.           if ((cursor - p_limit) * direction <= len)
  887.             break;    /* a small overrun is genuine */
  888.           cursor -= infinity; /* large overrun = hit */
  889.           i = dirlen - direction;
  890.           if ((int) trt)
  891.             {
  892.               while ((i -= direction) + direction != 0)
  893.             if (pat[i] != trt[*(cursor -= direction)])
  894.               break;
  895.             }
  896.           else
  897.             {
  898.               while ((i -= direction) + direction != 0)
  899.             if (pat[i] != *(cursor -= direction))
  900.               break;
  901.             }
  902.           cursor += dirlen - i - direction;    /* fix cursor */
  903.           if (i + direction == 0)
  904.             {
  905.               cursor -= direction;
  906.  
  907.               /* Make sure we have registers in which to store
  908.              the match position.  */
  909.               if (search_regs.num_regs == 0)
  910.             {
  911.               regoff_t *starts, *ends;
  912.  
  913.               starts =
  914.                 (regoff_t *) xmalloc (2 * sizeof (regoff_t));
  915.               ends =
  916.                 (regoff_t *) xmalloc (2 * sizeof (regoff_t));
  917.               BLOCK_INPUT;
  918.               re_set_registers (&searchbuf,
  919.                         &search_regs,
  920.                         2, starts, ends);
  921.               UNBLOCK_INPUT;
  922.             }
  923.  
  924.               search_regs.start[0]
  925.             = pos + cursor - p2 + ((direction > 0)
  926.                            ? 1 - len : 0);
  927.               search_regs.end[0] = len + search_regs.start[0];
  928.               XSET (last_thing_searched, Lisp_Buffer, current_buffer);
  929.               if ((n -= direction) != 0)
  930.             cursor += dirlen; /* to resume search */
  931.               else
  932.             return ((direction > 0)
  933.                 ? search_regs.end[0] : search_regs.start[0]);
  934.             }
  935.           else
  936.             cursor += stride_for_teases; /* <sigh> we lose -  */
  937.         }
  938.           pos += cursor - p2;
  939.         }
  940.       else
  941.         /* Now we'll pick up a clump that has to be done the hard */
  942.         /* way because it covers a discontinuity */
  943.         {
  944.           limit = ((direction > 0)
  945.                ? BUFFER_CEILING_OF (pos - dirlen + 1)
  946.                : BUFFER_FLOOR_OF (pos - dirlen - 1));
  947.           limit = ((direction > 0)
  948.                ? min (limit + len, lim - 1)
  949.                : max (limit - len, lim));
  950.           /* LIMIT is now the last value POS can have
  951.          and still be valid for a possible match.  */
  952.           while (1)
  953.         {
  954.           /* This loop can be coded for space rather than */
  955.           /* speed because it will usually run only once. */
  956.           /* (the reach is at most len + 21, and typically */
  957.           /* does not exceed len) */    
  958.           while ((limit - pos) * direction >= 0)
  959.             pos += BM_tab[FETCH_CHAR(pos)];
  960.           /* now run the same tests to distinguish going off the */
  961.           /* end, a match or a phony match. */
  962.           if ((pos - limit) * direction <= len)
  963.             break;    /* ran off the end */
  964.           /* Found what might be a match.
  965.              Set POS back to last (first if reverse) char pos.  */
  966.           pos -= infinity;
  967.           i = dirlen - direction;
  968.           while ((i -= direction) + direction != 0)
  969.             {
  970.               pos -= direction;
  971.               if (pat[i] != (((int) trt)
  972.                      ? trt[FETCH_CHAR(pos)]
  973.                      : FETCH_CHAR (pos)))
  974.             break;
  975.             }
  976.           /* Above loop has moved POS part or all the way
  977.              back to the first char pos (last char pos if reverse).
  978.              Set it once again at the last (first if reverse) char.  */
  979.           pos += dirlen - i- direction;
  980.           if (i + direction == 0)
  981.             {
  982.               pos -= direction;
  983.  
  984.               /* Make sure we have registers in which to store
  985.              the match position.  */
  986.               if (search_regs.num_regs == 0)
  987.             {
  988.               regoff_t *starts, *ends;
  989.  
  990.               starts =
  991.                 (regoff_t *) xmalloc (2 * sizeof (regoff_t));
  992.               ends =
  993.                 (regoff_t *) xmalloc (2 * sizeof (regoff_t));
  994.               BLOCK_INPUT;
  995.               re_set_registers (&searchbuf,
  996.                         &search_regs,
  997.                         2, starts, ends);
  998.               UNBLOCK_INPUT;
  999.             }
  1000.  
  1001.               search_regs.start[0]
  1002.             = pos + ((direction > 0) ? 1 - len : 0);
  1003.               search_regs.end[0] = len + search_regs.start[0];
  1004.               XSET (last_thing_searched, Lisp_Buffer, current_buffer);
  1005.               if ((n -= direction) != 0)
  1006.             pos += dirlen; /* to resume search */
  1007.               else
  1008.             return ((direction > 0)
  1009.                 ? search_regs.end[0] : search_regs.start[0]);
  1010.             }
  1011.           else
  1012.             pos += stride_for_teases;
  1013.         }
  1014.           }
  1015.       /* We have done one clump.  Can we continue? */
  1016.       if ((lim - pos) * direction < 0)
  1017.         return ((0 - n) * direction);
  1018.     }
  1019.       return pos;
  1020.     }
  1021. }
  1022.  
  1023. /* Given a string of words separated by word delimiters,
  1024.   compute a regexp that matches those exact words
  1025.   separated by arbitrary punctuation.  */
  1026.  
  1027. static Lisp_Object
  1028. wordify (string)
  1029.      Lisp_Object string;
  1030. {
  1031.   register unsigned char *p, *o;
  1032.   register int i, len, punct_count = 0, word_count = 0;
  1033.   Lisp_Object val;
  1034.  
  1035.   CHECK_STRING (string, 0);
  1036.   p = XSTRING (string)->data;
  1037.   len = XSTRING (string)->size;
  1038.  
  1039.   for (i = 0; i < len; i++)
  1040.     if (SYNTAX (p[i]) != Sword)
  1041.       {
  1042.     punct_count++;
  1043.     if (i > 0 && SYNTAX (p[i-1]) == Sword) word_count++;
  1044.       }
  1045.   if (SYNTAX (p[len-1]) == Sword) word_count++;
  1046.   if (!word_count) return build_string ("");
  1047.  
  1048.   val = make_string (p, len - punct_count + 5 * (word_count - 1) + 4);
  1049.  
  1050.   o = XSTRING (val)->data;
  1051.   *o++ = '\\';
  1052.   *o++ = 'b';
  1053.  
  1054.   for (i = 0; i < len; i++)
  1055.     if (SYNTAX (p[i]) == Sword)
  1056.       *o++ = p[i];
  1057.     else if (i > 0 && SYNTAX (p[i-1]) == Sword && --word_count)
  1058.       {
  1059.     *o++ = '\\';
  1060.     *o++ = 'W';
  1061.     *o++ = '\\';
  1062.     *o++ = 'W';
  1063.     *o++ = '*';
  1064.       }
  1065.  
  1066.   *o++ = '\\';
  1067.   *o++ = 'b';
  1068.  
  1069.   return val;
  1070. }
  1071.  
  1072. DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
  1073.   "sSearch backward: ",
  1074.   "Search backward from point for STRING.\n\
  1075. Set point to the beginning of the occurrence found, and return point.\n\
  1076. An optional second argument bounds the search; it is a buffer position.\n\
  1077. The match found must not extend before that position.\n\
  1078. Optional third argument, if t, means if fail just return nil (no error).\n\
  1079.  If not nil and not t, position at limit of search and return nil.\n\
  1080. Optional fourth argument is repeat count--search for successive occurrences.\n\
  1081. See also the functions `match-beginning', `match-end' and `replace-match'.")
  1082.   (string, bound, noerror, count)
  1083.      Lisp_Object string, bound, noerror, count;
  1084. {
  1085.   return search_command (string, bound, noerror, count, -1, 0);
  1086. }
  1087.  
  1088. DEFUN ("search-forward", Fsearch_forward, Ssearch_forward, 1, 4, "sSearch: ",
  1089.   "Search forward from point for STRING.\n\
  1090. Set point to the end of the occurrence found, and return point.\n\
  1091. An optional second argument bounds the search; it is a buffer position.\n\
  1092. The match found must not extend after that position.  nil is equivalent\n\
  1093.   to (point-max).\n\
  1094. Optional third argument, if t, means if fail just return nil (no error).\n\
  1095.   If not nil and not t, move to limit of search and return nil.\n\
  1096. Optional fourth argument is repeat count--search for successive occurrences.\n\
  1097. See also the functions `match-beginning', `match-end' and `replace-match'.")
  1098.   (string, bound, noerror, count)
  1099.      Lisp_Object string, bound, noerror, count;
  1100. {
  1101.   return search_command (string, bound, noerror, count, 1, 0);
  1102. }
  1103.  
  1104. DEFUN ("word-search-backward", Fword_search_backward, Sword_search_backward, 1, 4,
  1105.   "sWord search backward: ",
  1106.   "Search backward from point for STRING, ignoring differences in punctuation.\n\
  1107. Set point to the beginning of the occurrence found, and return point.\n\
  1108. An optional second argument bounds the search; it is a buffer position.\n\
  1109. The match found must not extend before that position.\n\
  1110. Optional third argument, if t, means if fail just return nil (no error).\n\
  1111.   If not nil and not t, move to limit of search and return nil.\n\
  1112. Optional fourth argument is repeat count--search for successive occurrences.")
  1113.   (string, bound, noerror, count)
  1114.      Lisp_Object string, bound, noerror, count;
  1115. {
  1116.   return search_command (wordify (string), bound, noerror, count, -1, 1);
  1117. }
  1118.  
  1119. DEFUN ("word-search-forward", Fword_search_forward, Sword_search_forward, 1, 4,
  1120.   "sWord search: ",
  1121.   "Search forward from point for STRING, ignoring differences in punctuation.\n\
  1122. Set point to the end of the occurrence found, and return point.\n\
  1123. An optional second argument bounds the search; it is a buffer position.\n\
  1124. The match found must not extend after that position.\n\
  1125. Optional third argument, if t, means if fail just return nil (no error).\n\
  1126.   If not nil and not t, move to limit of search and return nil.\n\
  1127. Optional fourth argument is repeat count--search for successive occurrences.")
  1128.   (string, bound, noerror, count)
  1129.      Lisp_Object string, bound, noerror, count;
  1130. {
  1131.   return search_command (wordify (string), bound, noerror, count, 1, 1);
  1132. }
  1133.  
  1134. DEFUN ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
  1135.   "sRE search backward: ",
  1136.   "Search backward from point for match for regular expression REGEXP.\n\
  1137. Set point to the beginning of the match, and return point.\n\
  1138. The match found is the one starting last in the buffer\n\
  1139. and yet ending before the place the origin of the search.\n\
  1140. An optional second argument bounds the search; it is a buffer position.\n\
  1141. The match found must start at or after that position.\n\
  1142. Optional third argument, if t, means if fail just return nil (no error).\n\
  1143.   If not nil and not t, move to limit of search and return nil.\n\
  1144. Optional fourth argument is repeat count--search for successive occurrences.\n\
  1145. See also the functions `match-beginning', `match-end' and `replace-match'.")
  1146.   (string, bound, noerror, count)
  1147.      Lisp_Object string, bound, noerror, count;
  1148. {
  1149.   return search_command (string, bound, noerror, count, -1, 1);
  1150. }
  1151.  
  1152. DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
  1153.   "sRE search: ",
  1154.   "Search forward from point for regular expression REGEXP.\n\
  1155. Set point to the end of the occurrence found, and return point.\n\
  1156. An optional second argument bounds the search; it is a buffer position.\n\
  1157. The match found must not extend after that position.\n\
  1158. Optional third argument, if t, means if fail just return nil (no error).\n\
  1159.   If not nil and not t, move to limit of search and return nil.\n\
  1160. Optional fourth argument is repeat count--search for successive occurrences.\n\
  1161. See also the functions `match-beginning', `match-end' and `replace-match'.")
  1162.   (string, bound, noerror, count)
  1163.      Lisp_Object string, bound, noerror, count;
  1164. {
  1165.   return search_command (string, bound, noerror, count, 1, 1);
  1166. }
  1167.  
  1168. DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 3, 0,
  1169.   "Replace text matched by last search with NEWTEXT.\n\
  1170. If second arg FIXEDCASE is non-nil, do not alter case of replacement text.\n\
  1171. Otherwise convert to all caps or cap initials, like replaced text.\n\
  1172. If third arg LITERAL is non-nil, insert NEWTEXT literally.\n\
  1173. Otherwise treat `\\' as special:\n\
  1174.   `\\&' in NEWTEXT means substitute original matched text.\n\
  1175.   `\\N' means substitute what matched the Nth `\\(...\\)'.\n\
  1176.        If Nth parens didn't match, substitute nothing.\n\
  1177.   `\\\\' means insert one `\\'.\n\
  1178. FIXEDCASE and LITERAL are optional arguments.\n\
  1179. Leaves point at end of replacement text.")
  1180.   (string, fixedcase, literal)
  1181.      Lisp_Object string, fixedcase, literal;
  1182. {
  1183.   enum { nochange, all_caps, cap_initial } case_action;
  1184.   register int pos, last;
  1185.   int some_multiletter_word;
  1186.   int some_lowercase;
  1187.   int some_uppercase_initial;
  1188.   register int c, prevc;
  1189.   int inslen;
  1190.  
  1191.   CHECK_STRING (string, 0);
  1192.  
  1193.   case_action = nochange;    /* We tried an initialization */
  1194.                 /* but some C compilers blew it */
  1195.  
  1196.   if (search_regs.num_regs <= 0)
  1197.     error ("replace-match called before any match found");
  1198.  
  1199.   if (search_regs.start[0] < BEGV
  1200.       || search_regs.start[0] > search_regs.end[0]
  1201.       || search_regs.end[0] > ZV)
  1202.     args_out_of_range (make_number (search_regs.start[0]),
  1203.                make_number (search_regs.end[0]));
  1204.  
  1205.   if (NILP (fixedcase))
  1206.     {
  1207.       /* Decide how to casify by examining the matched text. */
  1208.  
  1209.       last = search_regs.end[0];
  1210.       prevc = '\n';
  1211.       case_action = all_caps;
  1212.  
  1213.       /* some_multiletter_word is set nonzero if any original word
  1214.      is more than one letter long. */
  1215.       some_multiletter_word = 0;
  1216.       some_lowercase = 0;
  1217.       some_uppercase_initial = 0;
  1218.  
  1219.       for (pos = search_regs.start[0]; pos < last; pos++)
  1220.     {
  1221.       c = FETCH_CHAR (pos);
  1222.       if (LOWERCASEP (c))
  1223.         {
  1224.           /* Cannot be all caps if any original char is lower case */
  1225.  
  1226.           some_lowercase = 1;
  1227.           if (SYNTAX (prevc) != Sword)
  1228.         ;
  1229.           else
  1230.         some_multiletter_word = 1;
  1231.         }
  1232.       else if (!NOCASEP (c))
  1233.         {
  1234.           if (SYNTAX (prevc) != Sword)
  1235.         some_uppercase_initial = 1;
  1236.           else
  1237.         some_multiletter_word = 1;
  1238.         }
  1239.  
  1240.       prevc = c;
  1241.     }
  1242.  
  1243.       /* Convert to all caps if the old text is all caps
  1244.      and has at least one multiletter word.  */
  1245.       if (! some_lowercase && some_multiletter_word)
  1246.     case_action = all_caps;
  1247.       /* Capitalize each word, if the old text has a capitalized word.  */
  1248.       else if (some_uppercase_initial)
  1249.     case_action = cap_initial;
  1250.       else
  1251.     case_action = nochange;
  1252.     }
  1253.  
  1254.   /* We insert the replacement text before the old text, and then
  1255.      delete the original text.  This means that markers at the
  1256.      beginning or end of the original will float to the corresponding
  1257.      position in the replacement.  */
  1258.   SET_PT (search_regs.start[0]);
  1259.   if (!NILP (literal))
  1260.     Finsert (1, &string);
  1261.   else
  1262.     {
  1263.       struct gcpro gcpro1;
  1264.       GCPRO1 (string);
  1265.  
  1266.       for (pos = 0; pos < XSTRING (string)->size; pos++)
  1267.     {
  1268.       int offset = point - search_regs.start[0];
  1269.  
  1270.       c = XSTRING (string)->data[pos];
  1271.       if (c == '\\')
  1272.         {
  1273.           c = XSTRING (string)->data[++pos];
  1274.           if (c == '&')
  1275.         Finsert_buffer_substring
  1276.           (Fcurrent_buffer (),
  1277.            make_number (search_regs.start[0] + offset),
  1278.            make_number (search_regs.end[0] + offset));
  1279.           else if (c >= '1' && (unsigned)c <= search_regs.num_regs + '0')
  1280.         {
  1281.           if (search_regs.start[c - '0'] >= 1)
  1282.             Finsert_buffer_substring
  1283.               (Fcurrent_buffer (),
  1284.                make_number (search_regs.start[c - '0'] + offset),
  1285.                make_number (search_regs.end[c - '0'] + offset));
  1286.         }
  1287.           else
  1288.         insert_char ((unsigned char)c);
  1289.         }
  1290.       else
  1291.         insert_char ((unsigned char)c);
  1292.     }
  1293.       UNGCPRO;
  1294.     }
  1295.  
  1296.   inslen = point - (search_regs.start[0]);
  1297.   del_range (search_regs.start[0] + inslen, search_regs.end[0] + inslen);
  1298.  
  1299.   if (case_action == all_caps)
  1300.     Fupcase_region (make_number (point - inslen), make_number (point));
  1301.   else if (case_action == cap_initial)
  1302.     upcase_initials_region (make_number (point - inslen), make_number (point));
  1303.   return Qnil;
  1304. }
  1305.  
  1306. static Lisp_Object
  1307. match_limit (num, beginningp)
  1308.      Lisp_Object num;
  1309.      int beginningp;
  1310. {
  1311.   register int n;
  1312.  
  1313.   CHECK_NUMBER (num, 0);
  1314.   n = XINT (num);
  1315.   if (n < 0 || (unsigned)n >= search_regs.num_regs)
  1316.     args_out_of_range (num, make_number (search_regs.num_regs));
  1317.   if (search_regs.num_regs <= 0
  1318.       || search_regs.start[n] < 0)
  1319.     return Qnil;
  1320.   return (make_number ((beginningp) ? search_regs.start[n]
  1321.                             : search_regs.end[n]));
  1322. }
  1323.  
  1324. DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
  1325.   "Return position of start of text matched by last search.\n\
  1326. ARG, a number, specifies which parenthesized expression in the last regexp.\n\
  1327.  Value is nil if ARGth pair didn't match, or there were less than ARG pairs.\n\
  1328. Zero means the entire text matched by the whole regexp or whole string.")
  1329.   (num)
  1330.      Lisp_Object num;
  1331. {
  1332.   return match_limit (num, 1);
  1333. }
  1334.  
  1335. DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
  1336.   "Return position of end of text matched by last search.\n\
  1337. ARG, a number, specifies which parenthesized expression in the last regexp.\n\
  1338.  Value is nil if ARGth pair didn't match, or there were less than ARG pairs.\n\
  1339. Zero means the entire text matched by the whole regexp or whole string.")
  1340.   (num)
  1341.      Lisp_Object num;
  1342. {
  1343.   return match_limit (num, 0);
  1344.  
  1345. DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 0, 0,
  1346.   "Return a list containing all info on what the last search matched.\n\
  1347. Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.\n\
  1348. All the elements are markers or nil (nil if the Nth pair didn't match)\n\
  1349. if the last match was on a buffer; integers or nil if a string was matched.\n\
  1350. Use `store-match-data' to reinstate the data in this list.")
  1351.   ()
  1352. {
  1353.   Lisp_Object *data;
  1354.   int i, len;
  1355.  
  1356.   if (NILP (last_thing_searched))
  1357.     error ("match-data called before any match found");
  1358.  
  1359.   data = (Lisp_Object *) alloca ((2 * search_regs.num_regs)
  1360.                  * sizeof (Lisp_Object));
  1361.  
  1362.   len = -1;
  1363.   for (i = 0; (unsigned)i < search_regs.num_regs; i++)
  1364.     {
  1365.       int start = search_regs.start[i];
  1366.       if (start >= 0)
  1367.     {
  1368.       if (EQ (last_thing_searched, Qt))
  1369.         {
  1370.           XFASTINT (data[2 * i]) = start;
  1371.           XFASTINT (data[2 * i + 1]) = search_regs.end[i];
  1372.         }
  1373.       else if (XTYPE (last_thing_searched) == Lisp_Buffer)
  1374.         {
  1375.           data[2 * i] = Fmake_marker ();
  1376.           Fset_marker (data[2 * i],
  1377.                make_number (start),
  1378.                last_thing_searched);
  1379.           data[2 * i + 1] = Fmake_marker ();
  1380.           Fset_marker (data[2 * i + 1],
  1381.                make_number (search_regs.end[i]), 
  1382.                last_thing_searched);
  1383.         }
  1384.       else
  1385.         /* last_thing_searched must always be Qt, a buffer, or Qnil.  */
  1386.         abort ();
  1387.  
  1388.       len = i;
  1389.     }
  1390.       else
  1391.     data[2 * i] = data [2 * i + 1] = Qnil;
  1392.     }
  1393.   return Flist (2 * len + 2, data);
  1394. }
  1395.  
  1396.  
  1397. DEFUN ("store-match-data", Fstore_match_data, Sstore_match_data, 1, 1, 0,
  1398.   "Set internal data on last search match from elements of LIST.\n\
  1399. LIST should have been created by calling `match-data' previously.")
  1400.   (list)
  1401.      register Lisp_Object list;
  1402. {
  1403.   register int i;
  1404.   register Lisp_Object marker;
  1405.  
  1406.   if (!CONSP (list) && !NILP (list))
  1407.     list = wrong_type_argument (Qconsp, list);
  1408.  
  1409.   /* Unless we find a marker with a buffer in LIST, assume that this 
  1410.      match data came from a string.  */
  1411.   last_thing_searched = Qt;
  1412.  
  1413.   /* Allocate registers if they don't already exist.  */
  1414.   {
  1415.     int length = XFASTINT (Flength (list)) / 2;
  1416.  
  1417.     if ((unsigned)length > search_regs.num_regs)
  1418.       {
  1419.     if (search_regs.num_regs == 0)
  1420.       {
  1421.         search_regs.start
  1422.           = (regoff_t *) xmalloc (length * sizeof (regoff_t));
  1423.         search_regs.end
  1424.           = (regoff_t *) xmalloc (length * sizeof (regoff_t));
  1425.       }
  1426.     else
  1427.       {
  1428.         search_regs.start
  1429.           = (regoff_t *) xrealloc (search_regs.start,
  1430.                        length * sizeof (regoff_t));
  1431.         search_regs.end
  1432.           = (regoff_t *) xrealloc (search_regs.end,
  1433.                        length * sizeof (regoff_t));
  1434.       }
  1435.  
  1436.     BLOCK_INPUT;
  1437.     re_set_registers (&searchbuf, &search_regs, length,
  1438.               search_regs.start, search_regs.end);
  1439.     UNBLOCK_INPUT;
  1440.       }
  1441.   }
  1442.  
  1443.   for (i = 0; (unsigned)i < search_regs.num_regs; i++)
  1444.     {
  1445.       marker = Fcar (list);
  1446.       if (NILP (marker))
  1447.     {
  1448.       search_regs.start[i] = -1;
  1449.       list = Fcdr (list);
  1450.     }
  1451.       else
  1452.     {
  1453.       if (XTYPE (marker) == Lisp_Marker)
  1454.         {
  1455.           if (XMARKER (marker)->buffer == 0)
  1456.         XFASTINT (marker) = 0;
  1457.           else
  1458.         XSET (last_thing_searched, Lisp_Buffer,
  1459.               XMARKER (marker)->buffer);
  1460.         }
  1461.  
  1462.       CHECK_NUMBER_COERCE_MARKER (marker, 0);
  1463.       search_regs.start[i] = XINT (marker);
  1464.       list = Fcdr (list);
  1465.  
  1466.       marker = Fcar (list);
  1467.       if (XTYPE (marker) == Lisp_Marker
  1468.           && XMARKER (marker)->buffer == 0)
  1469.         XFASTINT (marker) = 0;
  1470.  
  1471.       CHECK_NUMBER_COERCE_MARKER (marker, 0);
  1472.       search_regs.end[i] = XINT (marker);
  1473.     }
  1474.       list = Fcdr (list);
  1475.     }
  1476.  
  1477.   return Qnil;  
  1478. }
  1479.  
  1480. /* Quote a string to inactivate reg-expr chars */
  1481.  
  1482. DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
  1483.   "Return a regexp string which matches exactly STRING and nothing else.")
  1484.   (str)
  1485.      Lisp_Object str;
  1486. {
  1487.   register unsigned char *in, *out, *end;
  1488.   register unsigned char *temp;
  1489.  
  1490.   CHECK_STRING (str, 0);
  1491.  
  1492.   temp = (unsigned char *) alloca (XSTRING (str)->size * 2);
  1493.  
  1494.   /* Now copy the data into the new string, inserting escapes. */
  1495.  
  1496.   in = XSTRING (str)->data;
  1497.   end = in + XSTRING (str)->size;
  1498.   out = temp; 
  1499.  
  1500.   for (; in != end; in++)
  1501.     {
  1502.       if (*in == '[' || *in == ']'
  1503.       || *in == '*' || *in == '.' || *in == '\\'
  1504.       || *in == '?' || *in == '+'
  1505.       || *in == '^' || *in == '$')
  1506.     *out++ = '\\';
  1507.       *out++ = *in;
  1508.     }
  1509.  
  1510.   return make_string (temp, out - temp);
  1511. }
  1512.  
  1513. _VOID_
  1514. syms_of_search ()
  1515. {
  1516.   searchbuf.allocated = 100;
  1517.   searchbuf.buffer = (unsigned char *) malloc (searchbuf.allocated);
  1518.   searchbuf.fastmap = search_fastmap;
  1519.  
  1520.   Qsearch_failed = intern ("search-failed");
  1521.   staticpro (&Qsearch_failed);
  1522.   Qinvalid_regexp = intern ("invalid-regexp");
  1523.   staticpro (&Qinvalid_regexp);
  1524.  
  1525.   Fput (Qsearch_failed, Qerror_conditions,
  1526.     Fcons (Qsearch_failed, Fcons (Qerror, Qnil)));
  1527.   Fput (Qsearch_failed, Qerror_message,
  1528.     build_string ("Search failed"));
  1529.  
  1530.   Fput (Qinvalid_regexp, Qerror_conditions,
  1531.     Fcons (Qinvalid_regexp, Fcons (Qerror, Qnil)));
  1532.   Fput (Qinvalid_regexp, Qerror_message,
  1533.     build_string ("Invalid regexp"));
  1534.  
  1535.   last_regexp = Qnil;
  1536.   staticpro (&last_regexp);
  1537.  
  1538.   last_thing_searched = Qnil;
  1539.   staticpro (&last_thing_searched);
  1540.  
  1541.   defsubr (&Sstring_match);
  1542.   defsubr (&Slooking_at);
  1543.   defsubr (&Sskip_chars_forward);
  1544.   defsubr (&Sskip_chars_backward);
  1545.   defsubr (&Sskip_syntax_forward);
  1546.   defsubr (&Sskip_syntax_backward);
  1547.   defsubr (&Ssearch_forward);
  1548.   defsubr (&Ssearch_backward);
  1549.   defsubr (&Sword_search_forward);
  1550.   defsubr (&Sword_search_backward);
  1551.   defsubr (&Sre_search_forward);
  1552.   defsubr (&Sre_search_backward);
  1553.   defsubr (&Sreplace_match);
  1554.   defsubr (&Smatch_beginning);
  1555.   defsubr (&Smatch_end);
  1556.   defsubr (&Smatch_data);
  1557.   defsubr (&Sstore_match_data);
  1558.   defsubr (&Sregexp_quote);
  1559. }
  1560.